<?php
/**
 * 仓库
 * 
 * Created	: 2010-10-11
 * Modified : 2010-10-15
 * @author  : 陈立强
 */
class Depot
{
	
	public static $cfg  = null;
	public static $cfgName = 'build/depot';
	
	public static $itemList = array();
	
	/**
	 * 读取用户仓库物品列表
	 * @param int $u_id 用户ID
	 * @param int|string $type 仓库物品类型 0-表示全部类型
	 * @param null|int|string $skill_id 物品技能类型ID
	 * @param int $pageNo 仓库分页编号 0-表示没有分页,显示全部
	 * @param array $itemIdList 物品ID列表
	 */
	public static function getList($uid, $type=0, $skill_id=null, $pageNo=1, $itemIdList=null, $where='')
	{
		global $DB, $L, $G, $m;
		
		$type = $type;
		$pageNo = (int)$pageNo;
		
		$pageSize = $G['depot_grid_page'];
		$list = array();
		if (!$where) {
			$where = 'uid='.$uid.' AND num<>0';
		} else {
			$where .= ' AND uid='.$uid.' AND num<>0';
		}
		
		if (is_int_string($type) && $type>0) {
			$where .= ' AND item_type='.(int)$type;
		} elseif (preg_match('~^(?:[\d]+\,)+[\d]+$~is', $type)) {
			$where .= ' AND item_type IN ('.$type.')';
		} elseif (!is_null($skill_id)) {
			$where .= ' AND skill_id='.(int)$skill_id;
		}
		if (is_array($itemIdList)) {
			foreach ($itemIdList as $item_id) {
				// ITEM_ID非法
				if (!is_int_string($item_id)) {
					return array(
						'val' => false,
						'msg' => $L['invalid_request']
					);
				}
			}
			$where .= ' AND item_id IN ('.join(',', $itemIdList).')';
		}
		
		$data = array();
		
		$sql = 'SELECT * FROM depot WHERE '.$where;
		if ($pageNo > 0) {
			$maxNum = $DB->getValue('SELECT depot_max_capacity FROM user WHERE uid='.$uid);
			$total = $DB->getCount('depot', $where);
			$curNum = $DB->getValue('SELECT SUM(num) FROM depot WHERE uid='.$uid);
			$pageNum = ceil($total/$pageSize);
			$start = ($pageNo-1)*$pageSize;
			$sql .= ' limit '.$start.', '.$pageSize;
			$data['cur_num'] = $curNum;
			$data['max_num'] = $maxNum;
			$data['cur_page'] = $pageNo;
			$data['max_page'] = $pageNum;
		}
		$arr = $DB->getList($sql);
		if (false === $arr) {
			return array(
				'val' => false,
				'msg' => $L['Failure']
			);
		}
		$itemList = C('item/item_list');
		foreach ($arr as $v) {
			$item = $itemList[$v['item_id']];
			$quality = $v['quality'];
			$minPrice = $m->get('marketMinPrice-'.$v['item_id'].'_'.$quality);
			$qualitySign = $G['id_quality'][$quality];
			$basePrice = $item['price'][$quality];
			if (!$minPrice) {
				$sql = 'SELECT min_price FROM market WHERE item_id='.$v['item_id'].' AND quality='.$quality;
				$minPrice = $DB->getValue($sql);
				if (!$minPrice) {
					$minPrice = $item['price'][$quality];
				}
				$m->set('marketMinPrice-'.$v['item_id'].'_'.$quality, $minPrice);
			}
			$v['min_price'] = $minPrice;
			$v['base_price'] = $basePrice;
			$v['title'] .= $qualitySign;
			$list[] = $v;
		}
		
		$data['list'] = $list;
		$data['free_grid'] = self::getFreeCapacity($uid);
		
		return array(
			'val'  => true,
			'data' => $data,
		);
	}
	
	/**
	 * 获取所有物品类别名称列表
	 * @param int $uid 用户ID,用户接口请求默认当前登录用户
	 */
	public static function getItemTypeList($uid)
	{
		$list = C('item/item_type_name');
		
		return array(
			'val'  => true,
			'data' => $list
		);
	}
	
	/**
	 * 物品存入仓库
	 * @param int $uid 用户ID
	 * @param array $data 物品进入仓库的一些参数item_id,num,quality
	 */
	public static function in($uid, $data)
	{
		global $DB, $L, $G;
		
		$num     = (int)$data['num'];
		$quality = (int)$data['quality'];
		
		$freeCapacity = self::getFreeCapacity($uid);
		if ($freeCapacity < $num) {
			return array(
				'val' => false,
				'msg' => $L['not_enough_grid_in_depot']
			);
		}
		
		$itemId		= (int)$data['item_id'];
		$itemType	= isset($data['item_type']) ? (int)$data['item_type'] : 0;
		$stack		= isset($data['stack']) ? (int)$data['stack'] : 1;
		$lvl		= isset($data['lvl']) ? (int)$data['lvl'] : 0;

		if (empty(self::$itemList)) {
			$titems   = C('item/item_list');
			$itemInfo = $titems[$itemId];
			self::$itemList = $titems;
		}
		if (isset($data['title'])) {
			$title = $data['title'];
		} else {
			$title = $itemInfo['title'];
		}
		
		$where = 'uid=:uid and item_id=:item_id and quality=:quality';
		$params = array(
			'uid'     => $uid,
			'item_id' => $itemId,
			'quality' => $quality
		);
		
		if ($stack) {
			$sql = 'SELECT depot_id,num,stack FROM depot WHERE '.$where;
			$depotInfo = $DB->getValue($sql, $params);
			$formerNum = (int)$depotInfo['num'];
			$num += $formerNum;
			if ($num > $G['item_max_stack']) {
				return array(
					'val' => false,
					'msg' => $L['item_is_overflow']
				);
			}
		}
		
		if (!$stack || !$depotInfo || !$depotInfo['stack']) {
			$data = array(
				'uid'		=> $uid,
				'item_id'	=> $itemId,
				'item_type' => $itemType,
				'title'		=> $title,
				'num'		=> $num,
				'stack'		=> $stack,
				'quality'	=> $quality,
				'lvl'		=> $lvl,
			);
			$ret = $depot_id = $DB->insert('depot', $data);
		} else {
			$data = array(
				'num' => $num
			);
			$where = 'depot_id='.$depotInfo['depot_id'];
			$ret = $DB->update('depot', $data, $where);
			$depot_id = $depotInfo['depot_id'];
		}
		
		$result['val'] = $ret;
		if ($ret) {
			$result['data']['depot_id'] = $depot_id;
		} else {
			$s = $itemId.': '.$title;
			$result['msg'] = sprintf($L['depot_in_failure'], $s);
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('depot_in', $data);
		}
		return $result;
	}
	
	/**
	 * 物品出库
	 * @param int $uid
	 * @param int $data array($depot_id => $num)
	 */
	public static function out($uid, $data)
	{
		global $DB, $L;
		if (empty($data)) {
			return array(
				'val' => false,
				'msg' => $L['depot_out_item_not_enough']
			);
		}
		$ids = array_keys($data);
		$ids = join(',', $ids);
		$sql = 'SELECT * FROM depot WHERE depot_id in ('.$ids.')';
		$list = $DB->getList($sql);
		if (empty($list)) {
			return array(
				'val' => false,
				'msg' => $L['depot_out_item_not_enough']
			);
		}
		$sql = '';
		foreach ($list as $v) {
			$num = $data[$v['depot_id']];
			if ($v['num'] < $num) {
				return array(
					'val' => false,
					'msg' => $L['depot_out_item_not_enough']
				);
			}
			$v['num'] -= $num;
			$where = 'depot_id='.$v['depot_id'];
			$sql  .= 'UPDATE depot SET num='.$v['num'].' WHERE '.$where.';';
		}
		$resultVal = $DB->exec($sql);
		if ($resultVal !== false) {
			$resultVal = true;
		}
		
		$result = array('val' => $resultVal);
		if ($resultVal) {
			User::changeValue($uid, time(), 'last_depot_out_time');
//			$result['data'] = self::getList($uid);
		} else {
			$result['msg'] = $L['Failure'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('depot_out', $data);
		}
		return $result;
	}
	
	/**
	 * 指定玩家的仓库剩余容量
	 * @param int $uid
	 */
	public static function getFreeCapacity($uid)
	{
		global $DB, $L, $G;
		$sql = 'SELECT sum(num) as cnt FROM depot WHERE uid='.$uid;
		$capacity = $DB->getValue($sql);
		if (false === $capacity) {
			return array(
				'val' => false,
				'msg' => $L['Failure']
			);
		}
		$sql = 'SELECT depot_max_capacity FROM user WHERE uid='.$uid;
		$maxCapacity = $DB->getValue($sql);
		if ($capacity >= $maxCapacity) {
			return 0;
		} else {
			return ($maxCapacity - $capacity);
		}
	}

	/**
	 * 获取指定仓库物品的信息
	 * @param int $uid
	 * @param int $depot_id
	 */
	public static function getInfo($uid, $depot_id)
	{
		global $DB, $L, $G;
		
		$depot_id = (int)$depot_id;
		
		$sql = 'SELECT * FROM depot WHERE depot_id='.(int)$depot_id;
		$info = $DB->getValue($sql);
		if (!$info) {
			return array(
				'val' => false,
				'msg' => $L['Unknow_item']
			);
		}
		
		if ($uid != $info['uid']) {
			return array(
				'val' => false,
				'msg' => $L['Invalid_uid']
			);
		}

		return $info;
	}
	
	/**
	 * 扩展仓库的容量
	 * @param int $uid
	 */
	public static function addCapacity($uid)
	{
		global $DB, $L, $G;
		
		$sql = 'SELECT ticket,add_depot_capacity_times,depot_max_capacity FROM user WHERE uid='.$uid;
		$user = $DB->getValue($sql);
		
		$addTimes = $user['add_depot_capacity_times'] + 1;
		// 仓库容量已达到最大上限,配置不存在 
		if ($user['depot_max_capacity'] >= $G['depot_max_capacity'] || !isset($G['add_depot_capacity_need_ticket'][$addTimes])) {
			return array(
				'val' => false,
				'msg' => $L['depot_capacity_is_max']
			);
		}
		$needTicket = $G['add_depot_capacity_need_ticket'][$addTimes];
		
		// 点券是否足够
		if ($user['ticket'] < $needTicket) {
			return array(
				'val' => false,
				'msg' => $L['depot_extend_ticket_not_enough']
			);
		}
		
		$DB->beginTransaction();
		
		// 扣除金钱
		$sql = 'UPDATE user set ticket=ticket-'.$needTicket.' WHERE uid='.$uid;
		$ret = $DB->exeSql($sql);
		
		if ($ret) {
			$sql = 'UPDATE user set add_depot_capacity_times=add_depot_capacity_times+1,
						depot_max_capacity=depot_max_capacity+'.$G['add_capacity_per_times'].' WHERE uid='.$uid;
			$ret = $DB->exeSql($sql);
		}
		
		$result['val'] = (boolean)$ret;
		if ($ret) {
			$DB->commit();
			$result['data'] = array(
				'depot_id' => $ret,
			);
		} else {
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$str = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('depot_add_capacity', $str);
		}

		return $result;
	}
}










